package com.ydj.cofig;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class PoolConfiguration {
    @Autowired
    private BeanFactory beanFactory;
    @Bean("monitorThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor monitorThreadPoolTaskExecutor() {

        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPoolExecutor.setCorePoolSize(10);
        //设置最大线程数
        threadPoolExecutor.setMaxPoolSize(20);
        //设置工作队列数量
        threadPoolExecutor.setQueueCapacity(100);
        //设置存活时间
        threadPoolExecutor.setKeepAliveSeconds(60);
        //是否允许超时
        threadPoolExecutor.setAllowCoreThreadTimeOut(true);
        //线程前缀名
        threadPoolExecutor.setThreadNamePrefix("monitor-thread-pool-");
        //设置拒绝策略
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //设置线程池关闭的时候等待所有的子任务执行完成才销毁对应的bean
        threadPoolExecutor.setWaitForTasksToCompleteOnShutdown(true);
        //初始化线程池
        threadPoolExecutor.initialize();
        return threadPoolExecutor;
    }
}
